DEPSDIR:=.deps
SOURCEDIR:=Source
BUILDDIR:=Build

#screw that!
CPP_FILES = $(shell cd $(SOURCEDIR) &&  find -iname "*.cpp" && cd ..)

#screw THAT!
#CPP_FILES = $(shell cat coolgame.kdevelop.filelist | grep "cpp" | sed "s:.*/::")

#watch order here, CPP_FILES set last because the others use it
OBJ_FILES := $(CPP_FILES:%.cpp=$(BUILDDIR)/%.o)
DEP_FILES := $(CPP_FILES:%.cpp=$(DEPSDIR)/%.d)
CPP_FILES := $(CPP_FILES:%.cpp=$(SOURCEDIR)/%.cpp)

BUILDDIRS := $(shell cd $(SOURCEDIR) && find -type d | grep -v "\.svn")

$(shell mkdir -p $(BUILDDIR))
$(shell cd $(BUILDDIR) && mkdir -p $(BUILDDIRS))
$(shell mkdir -p $(DEPSDIR))
$(shell cd $(DEPSDIR) && mkdir -p $(BUILDDIRS))

CFLAGS = `sdl-config --cflags` -posix -I/usr/X11R6/include -I/usr/include/freetype2 -I$(SOURCEDIR)/Include -IInclude
LDFLAGS = `sdl-config --libs` -lSDL_image -lSDL_net -lGL -lpng -lGLU -lfreetype -lrt -lboost_thread-mt -O3 -lboost_program_options
DBGFLAGS = -O0 -g
RM   = /bin/rm -f
ifneq ($(DEBUG),0)
	CFLAGS+=$(DBGFLAGS)
else
	ifeq ($(USER), dafox)
		CFLAGS+=-march=pentium-m -O3 -pipe -fomit-frame-pointer -falign-functions=32 -fweb -ffast-math
	else ifeq ($(USER), simon)
		CFLAGS+=-march=athlon-xp -O3 -pipe -fomit-frame-pointer -ffast-math -fweb -fno-cprop-registers -frename-registers
	else
		CFLAGS+=-O3 -pipe -fomit-frame-pointer -ffast-math
	endif
endif

all: CoolGame

CoolGame: $(BUILDDIR)/coolgame

run: CoolGame
	$(BUILDDIR)/coolgame

$(BUILDDIR)/coolgame: .flags $(OBJ_FILES)
	@echo [Linking] CoolGame
	@g++ $(OBJ_FILES) $(LDFLAGS) -o $(BUILDDIR)/coolgame

.flags: $(CPP_FILES)
	@rm -f .flags
	@echo "" >> .flags
	@echo "CFLAGS : $(CFLAGS)"  >> .flags
	@echo "LDFLAGS: $(LDFLAGS)" >> .flags
	@echo "" >> .flags
	@cat .flags

$(BUILDDIR)/%.o: $(SOURCEDIR)/%.cpp
	@echo [Compiling] $*
	@g++ -c -MD $< -o $@ $(CFLAGS)
# next line from http://make.paulandlesley.org/autodep.html
	@cp $(BUILDDIR)/$*.d $(BUILDDIR)/$*.dd; \
	  sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
	  -e '/^$$/ d' -e 's/$$/ :/' < $(BUILDDIR)/$*.dd >> $(BUILDDIR)/$*.d; \
	  rm -f $(BUILDDIR)/$*.dd
	@mv $(BUILDDIR)/$*.d $(DEPSDIR)/$*.d

clean:
	@echo [Cleaning]
	@$(RM) -f *~ $(SOURCEDIR)/*~ $(OBJ_FILES) $(DEP_FILES) $(BUILDDIR)/CoolGame .flags

cleaner: clean
	@echo [Cleaner-ing]
	@$(RM) $(BUILDDIR)/CoolGame $(BUILDDIR)/*.o $(DEPSDIR)/*.d $(BUILDDIR)/*.d

-include $(DEP_FILES)
